import { Tabs, Popup } from 'antd-mobile'

import { useState } from 'react'
import { useInitialState } from '@/utils/use-initial-state'
import { useDispatch, useSelector } from 'react-redux'
import { RootState } from '@/types/store'
import { Dispatch } from 'redux'

import { getChannels, toggleChannels } from '@/store/actions/home'
import ArticleList from './components/ArticleList'
import Channels from './Channels'

import { Icon } from '@/components/Icon'
import styles from './index.module.scss'
import { useHistory } from 'react-router-dom'

const Home = () => {
  const { channels } = useInitialState(getChannels, 'home')
  const [channelVisible, setChannelVisible] = useState(false)
  const { channelActionKey } = useSelector((state: RootState) => state.home)
  const history = useHistory()
  const dispatch = useDispatch<Dispatch<any>>()
  const onChannelShow = () => {
    setChannelVisible(true)
  }
  const onChannelHide = () => {
    setChannelVisible(false)
  }
  const changeTab = (key: string) => {
    console.log(key)
    dispatch(toggleChannels(+key))
  }
  return (
    <div className={styles.root}>
      {/* 频道 Tabs 列表 */}
      {channels.length > 0 && (
        <Tabs
          className="tabs"
          activeLineMode="fixed"
          activeKey={channelActionKey + ''}
          onChange={changeTab}
          style={{
            '--fixed-active-line-width': '20px',
          }}
        >
          {/*  */}
          {channels.map((item) => (
            <Tabs.Tab forceRender title={item.name} key={item.id}>
              <ArticleList channelId={item.id} />
            </Tabs.Tab>
          ))}
        </Tabs>
      )}

      <div className="tabs-opration">
        <Icon type="iconbtn_search" onClick={() => history.push('/search')} />
        <Icon type="iconbtn_channel" onClick={onChannelShow} />
      </div>

      <Popup visible={channelVisible} className="channel-popup" position="left">
        <Channels onClose={onChannelHide}></Channels>
      </Popup>
    </div>
  )
}

export default Home
